<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">最新文章</h1>

    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <svg class="animate-spin h-8 w-8 text-[#C32A31]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
    </div>

    <!-- 错误信息 -->
    <div v-else-if="error" class="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
      <div class="flex">
        <div class="flex-shrink-0">
          <svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="ml-3">
          <p class="text-sm text-red-700">{{ error }}</p>
        </div>
      </div>
    </div>

    <!-- 文章列表 -->
    <div v-else-if="articles.length > 0" class="space-y-6">
      <div v-for="article in articles" :key="article.newsId" class="bg-white shadow overflow-hidden sm:rounded-lg hover:shadow-md transition-shadow duration-200">
        <div class="px-4 py-5 sm:px-6">
          <h3 class="text-lg leading-6 font-medium text-[#C32A31]">
            <router-link :to="`/news/${article.newsId}`" class="hover:underline">
              {{ article.title }}
            </router-link>
          </h3>
          <p class="mt-1 max-w-2xl text-sm text-gray-500">
            {{ formatDate(article.pubTime) }} | {{ article.category }}
          </p>
          <p class="mt-3 text-sm text-gray-700 line-clamp-3">
            {{ article.contentPreview || (article.contentText ? article.contentText.substring(0, 200) + '...' : '无内容摘要') }}
          </p>
          <div class="mt-3">
            <router-link :to="`/news/${article.newsId}`" class="text-sm font-medium text-[#C32A31] hover:text-[#991E29]">
              阅读全文 &rarr;
            </router-link>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div class="mt-6 flex flex-col sm:flex-row justify-center items-center gap-4">
        <div class="flex items-center text-sm text-gray-700">
          <span>共 {{ totalPages }} 页，当前第</span>
          <input
            v-model.number="pageInput"
            type="number"
            min="1"
            :max="totalPages"
            class="w-12 mx-2 px-2 py-1 border border-gray-300 rounded text-center focus:ring-[#C32A31] focus:border-[#C32A31]"
            @keyup.enter="goToPage"
          >
          <span>页</span>
        </div>
        
        <nav class="flex items-center gap-1">
          <button
            @click="changePage(1)"
            :disabled="currentPage <= 1"
            class="px-3 py-1 border rounded text-sm"
            :class="currentPage <= 1 ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            首页
          </button>
          <button
            @click="changePage(currentPage - 1)"
            :disabled="currentPage <= 1"
            class="px-3 py-1 border rounded text-sm"
            :class="currentPage <= 1 ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            上一页
          </button>
          <button
            @click="changePage(currentPage + 1)"
            :disabled="!hasMorePages"
            class="px-3 py-1 border rounded text-sm"
            :class="!hasMorePages ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            下一页
          </button>
          <button
            @click="changePage(totalPages)"
            :disabled="currentPage >= totalPages"
            class="px-3 py-1 border rounded text-sm"
            :class="currentPage >= totalPages ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            尾页
          </button>
        </nav>
      </div>
    </div>

    <!-- 无结果提示 -->
    <div v-else class="bg-white shadow overflow-hidden sm:rounded-lg p-6 text-center">
      <p class="text-gray-500">暂无文章</p>
      <p class="mt-2 text-sm text-gray-500">请稍后再试或浏览我们的<router-link to="/" class="text-[#C32A31] hover:underline">首页</router-link></p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { articleApi } from '../../utils/api';

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(true);
const error = ref(null);
const articles = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalResults = ref(0);
const totalPages = ref(1);
const pageInput = ref(1);

// 监听当前页码变化
watch(currentPage, (newVal) => {
  pageInput.value = newVal;
});

// 跳转到指定页码
const goToPage = () => {
  if (!pageInput.value || pageInput.value < 1) {
    pageInput.value = 1;
  } else if (pageInput.value > totalPages.value) {
    pageInput.value = totalPages.value;
  }
  changePage(pageInput.value);
};

// 计算属性
const hasMorePages = computed(() => {
  return currentPage.value < totalPages.value;
});

// 处理分页数据
const handlePaginationData = (result) => {
  // 检查响应是否为空或非对象
  if (!result || typeof result !== 'object') {
    console.error('Invalid response format:', result);
    return false;
  }

  // 情况1: 直接返回分页对象 {list: [...], total: number, pageNum: number, pageSize: number, pages: number}
  if (result.list && Array.isArray(result.list)) {
    articles.value = result.list;
    totalResults.value = result.total || 0;
    totalPages.value = result.pages || 1;
    return true;
  }

  // 情况2: 标准响应格式 {code: 200, data: {...}}
  if (result.code !== undefined) {
    if (result.code !== 200) {
      error.value = result.msg || '请求失败';
      return false;
    }

    // 处理标准响应中的数据
    if (result.data && typeof result.data === 'object') {
      // 如果data是分页对象格式
      if (result.data.list) {
        articles.value = result.data.list || [];
        totalResults.value = result.data.total || 0;
        totalPages.value = result.data.pages || 1;
      } else if (Array.isArray(result.data)) {
        // 如果data是数组
        articles.value = result.data;
      } else {
        // 其他对象格式
        articles.value = [];
      }
      return true;
    } else if (Array.isArray(result.data)) {
      // 直接返回数组
      articles.value = result.data;
      return true;
    }
  }

  // 情况3: 直接返回数组
  if (Array.isArray(result)) {
    articles.value = result;
    return true;
  }

  // 情况4: 未知格式
  console.warn('Unexpected response format:', result);
  articles.value = [];
  return false;
};

// 获取文章列表
const fetchArticles = async () => {
  loading.value = true;
  error.value = null;

  try {
    const result = await articleApi.getArticleList({
      limit: pageSize.value,
      page: currentPage.value
    });

    if (!handlePaginationData(result)) {
      error.value = '获取文章列表失败';
    }
  } catch (err) {
    console.error('Error fetching articles:', err);
    error.value = '获取文章列表失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

  // 切换页码
  const changePage = (page) => {
    // 验证页码范围
    if (page < 1) return;
    if (page > totalPages.value) return;

    currentPage.value = page;

    // 更新URL参数，使用replace避免在浏览器历史中创建新条目
    router.replace({
      query: {
        ...route.query,
        page
      }
    });

    // 获取新页面的文章
    fetchArticles();
    
    // 平滑滚动回页面顶部
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  };

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';

  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// 检查URL中的页面参数
const checkUrlParams = () => {
  const page = parseInt(route.query.page);
  if (page && !isNaN(page) && page > 0) {
    currentPage.value = page;
  }
};

// 页面加载时获取文章列表
onMounted(() => {
  checkUrlParams();
  fetchArticles();
});
</script>

<style scoped>
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
